import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import { USER_INFO } from '@/utils/constant';

import home from './home'; //首页
import data from './data'; //数据
import form from './form'; //表单
import detail from './detail'; //详情
import result from './result'; //结果页
import abnormal from './abnormal'; //异常页
import personal from './personal'; //个人
import system from './system'; //系统
import tools from './tools'; //工具

const login = () => import('@/views/login/index.vue');
const index = () => import('@/views/index.vue');
const NotFound = () => import('@/views/not-found/index.vue');

export const pages = [home, data, form, detail, result, abnormal, personal, system, tools]; //这里的顺序会影响页面主菜单的顺序

const routes: RouteRecordRaw[] = [
  { path: '/', redirect: '/home' },
  {
    path: '/login',
    name: 'login',
    meta: {
      title: '登录'
    },
    component: login
  },
  {
    path: '/index',
    name: 'index',
    component: index,
    children: [...pages]
  },
  { path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound }
];

const router = createRouter({
  history: createWebHistory('/element/'),
  routes: routes,
  scrollBehavior() {
    return { top: 0 };
  }
});

router.beforeEach((to) => {
  let user = localStorage.getItem(USER_INFO);

  if (to.name !== 'login' && !user) {
    sessionStorage.setItem('source_name', to.name as string);
    return { name: 'login' };
  }
});

export default router;
